import router from './index' // 路由实例
import { getRoutesApi } from '../api/auth'
import { RouterView } from 'vue-router'
import { useUserStore } from '@/store/auth'
// Vite 按目录扫描所有 .vue 组件
const modules = import.meta.glob('../views/**/*.vue')
export function transformRoute(route: any) {
  let componentImporter = null

  if (route.type === 0) {
    // 父级菜单用 RouterView 组件作为占位
    componentImporter = () => Promise.resolve(RouterView)
  } else if (route.component) {
    // 路径要和 modules 的 key 完全匹配，注意路径格式
    // 例如 route.component = 'auth/admin/index.vue'
    const path = `../views/${route.component}.vue`

    componentImporter = modules[path]
    console
    if (!componentImporter) {
      console.warn(`[路由组件] 未找到路径: ${path}，使用默认404组件`)
      componentImporter = () => import('@/views/404.vue')
    }
  } else {
    // 没有 component 字段，兜底使用 RouterView 或404
    componentImporter = () => Promise.resolve(RouterView)
  }
  let query = {}
  if (route.query) {
    query = route.query
    //格式转换 通过 = 转换为对象
    query = Object.fromEntries(new URLSearchParams(query))
  }
  return {
    path: route.path,
    name: route.name,
    component: () => componentImporter(),

    meta: {
      title: route.name,
      icon: route.icon,
      show_type: route.show_type,
      query,
    },
    children: route.children ? route.children.map(transformRoute) : [],
  }
}

/**
 * 从 API 加载路由
 */
export async function loadRoutesFromAPI() {
  try {
    const res = await getRoutesApi()
    const routes = res.data.menu.map(transformRoute)
    useUserStore().setPermission(res.data.permissions)
    routes.forEach((route: any) => {
      router.addRoute('Layout', route)
    })
  } catch (error) {
    console.error('加载路由失败:', error)
  }
}
